#import "GameEngine.h"

@interface GameEngine ()

@property (nonatomic, assign) GameState gameState;
@property (nonatomic, assign) NSInteger playerHealth;
@property (nonatomic, assign) NSInteger playerWeapon;
@property (nonatomic, assign) NSInteger enemiesKilled;
@property (nonatomic, assign) NSInteger bossHealth;
@property (nonatomic, strong) Position *playerPosition;
@property (nonatomic, strong) NSMutableArray<NSMutableArray<GridItem *> *> *grids;
@property (nonatomic, assign) NSInteger gridSize;

@end

@implementation GameEngine

- (instancetype)init {
    self = [super init];
    if (self) {
        _gridSize = 4;
        [self setupNewGame];
    }
    return self;
}

- (void)setupNewGame {
    self.playerHealth = 10;
    self.playerWeapon = 0;
    self.enemiesKilled = 0;
    self.bossHealth = 40; // 4次击杀需要，每次10点血
    self.gameState = GameStatePlaying;
    
    // 初始化网格
    self.grids = [NSMutableArray arrayWithCapacity:self.gridSize];
    for (NSInteger i = 0; i < self.gridSize; i++) {
        NSMutableArray *row = [NSMutableArray arrayWithCapacity:self.gridSize];
        for (NSInteger j = 0; j < self.gridSize; j++) {
            GridItem *item = [[GridItem alloc] initWithType:GridTypeEmpty value:0 
                                                   position:[[Position alloc] initWithRow:i column:j]];
            [row addObject:item];
        }
        [self.grids addObject:row];
    }
    
    // 设置玩家初始位置（右上角）
    self.playerPosition = [[Position alloc] initWithRow:0 column:self.gridSize - 1];
    [self updateGridAtPosition:self.playerPosition withType:GridTypePlayer value:0];
    
    // 初始填充网格
    [self fillEmptyGrids];
}

- (void)fillEmptyGrids {
    for (NSInteger i = 0; i < self.gridSize; i++) {
        for (NSInteger j = 0; j < self.gridSize; j++) {
            Position *pos = [[Position alloc] initWithRow:i column:j];
            GridItem *item = [self gridItemAtPosition:pos];
            if (item.type == GridTypeEmpty) {
                [self generateRandomGridItemAtPosition:pos];
            }
        }
    }
}

- (void)generateRandomGridItemAtPosition:(Position *)position {
    // 概率分布：武器30%，血瓶30%，敌人40%
    NSInteger random = arc4random_uniform(100);
    GridType type;
    NSInteger value;
    
    if (random < 30) {
        type = GridTypeWeapon;
        value = arc4random_uniform(3) + 1; // 1-3
    } else if (random < 60) {
        type = GridTypeHealthPotion;
        value = arc4random_uniform(2) + 2; // 2-3
    } else {
        type = GridTypeEnemy;
        value = arc4random_uniform(3) + 1; // 1-3
    }
    
    [self updateGridAtPosition:position withType:type value:value];
}

- (void)updateGridAtPosition:(Position *)position withType:(GridType)type value:(NSInteger)value {
    GridItem *newItem = [[GridItem alloc] initWithType:type value:value position:position];
    self.grids[position.row][position.column] = newItem;
    [self.delegate gridDidUpdateAtPosition:position];
}

- (GridItem *)gridItemAtPosition:(Position *)position {
    if (position.row >= 0 && position.row < self.gridSize && 
        position.column >= 0 && position.column < self.gridSize) {
        return self.grids[position.row][position.column];
    }
    return nil;
}

- (BOOL)isValidMove:(Position *)position {
    if (self.gameState != GameStatePlaying) return NO;
    
    // 检查边界
    if (position.row < 0 || position.row >= self.gridSize || 
        position.column < 0 || position.column >= self.gridSize) {
        return NO;
    }
    
    // 只能移动到相邻格子
    NSInteger rowDiff = ABS(position.row - self.playerPosition.row);
    NSInteger colDiff = ABS(position.column - self.playerPosition.column);
    
    return (rowDiff == 1 && colDiff == 0) || (rowDiff == 0 && colDiff == 1);
}

- (void)movePlayerToPosition:(Position *)position {
    if (![self isValidMove:position]) return;
    
    GridItem *targetItem = [self gridItemAtPosition:position];
    
    // 处理目标格子
    switch (targetItem.type) {
        case GridTypeWeapon:
            [self handleWeaponPickup:targetItem];
            break;
        case GridTypeHealthPotion:
            [self handleHealthPotion:targetItem];
            break;
        case GridTypeEnemy:
            [self handleEnemy:targetItem];
            break;
        case GridTypeBoss:
            [self handleBoss:targetItem];
            break;
        default:
            break;
    }
    
    // 移动玩家
    [self updateGridAtPosition:self.playerPosition withType:GridTypeEmpty value:0];
    self.playerPosition = position;
    [self updateGridAtPosition:self.playerPosition withType:GridTypePlayer value:0];
    
    // 刷新空出的格子
    [self fillEmptyGrids];
    
    [self.delegate playerStatsDidChange];
    [self checkGameState];
}

- (void)handleWeaponPickup:(GridItem *)weapon {
    self.playerWeapon += weapon.value;
    [self.delegate showMessage:[NSString stringWithFormat:@"获得武器 +%ld!", (long)weapon.value]];
}

- (void)handleHealthPotion:(GridItem *)potion {
    self.playerHealth += potion.value;
    [self.delegate showMessage:[NSString stringWithFormat:@"恢复生命 +%ld!", (long)potion.value]];
}

- (void)handleEnemy:(GridItem *)enemy {
    NSInteger enemyPower = enemy.value;
    NSInteger damage = enemyPower;
    
    // 优先消耗武器点数
    if (self.playerWeapon > 0) {
        NSInteger weaponUsed = MIN(self.playerWeapon, enemyPower);
        self.playerWeapon -= weaponUsed;
        damage -= weaponUsed;
    }
    
    // 剩余伤害消耗血量
    if (damage > 0) {
        self.playerHealth -= damage;
    }
    
    if (self.playerHealth > 0) {
        [self.delegate showMessage:[NSString stringWithFormat:@"击败敌人! 消耗:%ld", (long)enemyPower]];
        self.enemiesKilled++;
        
        // 每击败3个敌人刷新Boss
        if (self.enemiesKilled % 3 == 0) {
            [self spawnBoss];
        }
    }
}

- (void)handleBoss:(GridItem *)boss {
    NSInteger bossPower = 3; // Boss固定3点攻击力
    NSInteger damage = bossPower;
    
    // 优先消耗武器点数
    if (self.playerWeapon > 0) {
        NSInteger weaponUsed = MIN(self.playerWeapon, bossPower);
        self.playerWeapon -= weaponUsed;
        damage -= weaponUsed;
    }
    
    // 剩余伤害消耗血量
    if (damage > 0) {
        self.playerHealth -= damage;
    }
    
    if (self.playerHealth > 0) {
        self.bossHealth -= 10;
        [self.delegate showMessage:@"击败Boss! Boss血量-10"];
        
        if (self.bossHealth <= 0) {
            self.gameState = GameStateWin;
            [self.delegate showMessage:@"恭喜! 你击败了最终Boss!"];
        }
    }
}

- (void)spawnBoss {
    // 在随机空位置生成Boss
    NSMutableArray *emptyPositions = [NSMutableArray array];
    
    for (NSInteger i = 0; i < self.gridSize; i++) {
        for (NSInteger j = 0; j < self.gridSize; j++) {
            Position *pos = [[Position alloc] initWithRow:i column:j];
            GridItem *item = [self gridItemAtPosition:pos];
            if (item.type == GridTypeEmpty) {
                [emptyPositions addObject:pos];
            }
        }
    }
    
    if (emptyPositions.count > 0) {
        NSInteger randomIndex = arc4random_uniform((uint32_t)emptyPositions.count);
        Position *bossPos = emptyPositions[randomIndex];
        [self updateGridAtPosition:bossPos withType:GridTypeBoss value:3];
        [self.delegate showMessage:@"Boss出现了!"];
    }
}

- (void)checkGameState {
    if (self.playerHealth <= 0) {
        self.gameState = GameStateLose;
        [self.delegate showMessage:@"游戏结束! 你被击败了!"];
    }
    
    [self.delegate gameStateDidChange];
}

- (void)restartGame {
    [self setupNewGame];
    [self.delegate gameStateDidChange];
    [self.delegate playerStatsDidChange];
}

@end
